package com.ruoyi.business.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.business.domain.JtProductCategory;
import com.ruoyi.business.domain.JtProductSn;
import com.ruoyi.business.service.IJtProductCategoryService;
import com.ruoyi.business.utils.ProductUtil;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.utils.JtImageUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.JtProduct;
import com.ruoyi.business.service.IJtProductService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品信息Controller
 * 
 * @author Alan Zhang
 * @date 2025-05-22
 */
@Controller
@RequestMapping("/business/product")
public class JtProductController extends BaseController
{
    private String prefix = "business/product";

    @Autowired
    private IJtProductService jtProductService;
    @Autowired
    private IJtProductCategoryService productCategoryService;
    @Autowired
    private ServerConfig serverConfig;

    @RequiresPermissions("business:product:view")
    @GetMapping()
    public String product()
    {
        return prefix + "/product";
    }

    /**
     * 查询产品信息列表
     */
    @RequiresPermissions("business:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(JtProduct jtProduct)
    {
        startPage();
        List<JtProduct> list = jtProductService.selectJtProductList(jtProduct);
        return getDataTable(list);
    }


    @RequiresPermissions("business:product:view")
    @GetMapping("/select")
    public String selectProduct()
    {
        return prefix + "/selectProduct";
    }

    @RequiresPermissions("business:product:view")
    @GetMapping("/purchase/select")
    public String selectPurchaseProduct()
    {
        return prefix + "/selectInputProduct";
    }

    /**
     * 导出产品信息列表
     */
    @RequiresPermissions("business:product:export")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(JtProduct jtProduct)
    {
        List<JtProduct> list = jtProductService.selectJtProductList(jtProduct);
        ExcelUtil<JtProduct> util = new ExcelUtil<JtProduct>(JtProduct.class);
        return util.exportExcel(list, "产品信息数据");
    }

    /**
     * 新增产品信息
     */
    @RequiresPermissions("business:product:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存产品信息
     */
    @RequiresPermissions("business:product:add")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addSave(JtProduct jtProduct, MultipartFile file) throws IOException {
        if(StringUtils.isNotEmpty(jtProduct.getProductCode())){
            boolean res = ProductUtil.checkProductNo(jtProduct.getProductCode());
            if(res){
                return AjaxResult.error("商品编码不能包含特殊字符：逗号、空格");
            }
        }
        //检查
        JtProduct param = new JtProduct();
        param.setProductCode(jtProduct.getProductCode());
        List<JtProduct> jtProductList = jtProductService.selectJtProductList(param);
        if(jtProductList.size() > 0){
            return AjaxResult.error("商品编码重复！");
        }
        if(StringUtils.isNotEmpty(jtProduct.getStyleNo())){
            boolean res = ProductUtil.checkProductNo(jtProduct.getStyleNo());
            if(res){
                return AjaxResult.error("款式编码不能包含特殊字符：逗号、空格");
            }
        }
        if (file != null) {
            jtProduct.setImageUrl(JtImageUtil.uploadProduct(file, true));

            //缩略图
            jtProduct.setThumbnailUrl(JtImageUtil.uploadProductThumbnail(file, true));
        }
        return toAjax(jtProductService.insertJtProduct(jtProduct));
    }

    /**
     * 修改产品信息
     */
    @RequiresPermissions("business:product:edit")
    @GetMapping("/edit/{productId}")
    public String edit(@PathVariable("productId") Long productId, ModelMap mmap)
    {
        JtProduct jtProduct = jtProductService.selectJtProductByProductId(productId);
        mmap.put("jtProduct", jtProduct);
        //分类
        JtProductCategory paramCategory = new JtProductCategory();
        List<JtProductCategory> categoryList = productCategoryService.selectJtProductCategoryList(paramCategory);
        mmap.put("categoryList", categoryList);
        return prefix + "/edit";
    }

    /**
     * 修改保存产品信息
     */
    @RequiresPermissions("business:product:edit")
    @Log(title = "产品信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(JtProduct jtProduct,@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        if(StringUtils.isNotEmpty(jtProduct.getProductCode())){
            boolean res = ProductUtil.checkProductNo(jtProduct.getProductCode());
            if(res){
                return AjaxResult.error("商品编码不能包含特殊字符：逗号、空格");
            }
        }
        if(StringUtils.isNotEmpty(jtProduct.getStyleNo())){
            boolean res = ProductUtil.checkProductNo(jtProduct.getStyleNo());
            if(res){
                return AjaxResult.error("款式编码不能包含特殊字符：逗号、空格");
            }
        }
        if (file != null) {
            jtProduct.setImageUrl(JtImageUtil.uploadProduct(file, true));

            //删除源文件
            JtProduct jtProductDb = jtProductService.selectJtProductByProductId(jtProduct.getProductId());
            String oldImageUrl = jtProductDb.getImageUrl();
            if(StringUtils.isEmpty(oldImageUrl)){
                JtImageUtil.deleteFile(oldImageUrl);
            }

            //缩略图
            jtProduct.setThumbnailUrl(JtImageUtil.uploadProductThumbnail(file, true));
            //删除源文件
            String oldThumbnailUrl = jtProductDb.getThumbnailUrl();
            if(StringUtils.isEmpty(oldThumbnailUrl)){
                JtImageUtil.deleteFile(oldThumbnailUrl);
            }
        }
        return toAjax(jtProductService.updateJtProduct(jtProduct));
    }

    /**
     * 删除产品信息
     */
    @RequiresPermissions("business:product:remove")
    @Log(title = "产品信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(jtProductService.deleteJtProductByProductIds(ids));
    }


    /**
     * 上传图片请求（单个）
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadProductDetailPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 模板 商品信息
     * @return
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<JtProduct> util = new ExcelUtil<>(JtProduct.class);
        return util.importTemplateExcel( "商品导入");
    }

    /**
     * 模板 序列号
     * @return
     */
    @GetMapping("/importSnTemplate")
    @ResponseBody
    public AjaxResult importSnTemplate()
    {
        ExcelUtil<JtProductSn> util = new ExcelUtil<>(JtProductSn.class);
        return util.importTemplateExcel("商品序列号导入");
    }


    @Log(title = "商品-导入", businessType = BusinessType.IMPORT)
    @RequiresPermissions("business:product:edit")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean isUpdateSupport) throws Exception
    {
        ExcelUtil<JtProduct> util = new ExcelUtil<>(JtProduct.class);
        List<JtProduct> list = util.importExcel(file.getInputStream());
        String optName = ShiroUtils.getSysUser().getUserName();
        String message = jtProductService.importProductInfo(list, optName, isUpdateSupport);
        return AjaxResult.success(message);
    }


    @Log(title = "商品序列号-导入", businessType = BusinessType.IMPORT)
    @RequiresPermissions("business:product:edit")
    @PostMapping("/importSnData/{productId}")
    @ResponseBody
    public AjaxResult importSnData(MultipartFile file,@PathVariable("productId") Long productId, boolean isUpdateSupport) throws Exception
    {
        ExcelUtil<JtProductSn> util = new ExcelUtil<>(JtProductSn.class);
        List<JtProductSn> list = util.importExcel(file.getInputStream());
        String optName = ShiroUtils.getSysUser().getUserName();
        String message = jtProductService.importProductSn(list, productId, optName, isUpdateSupport);
        return AjaxResult.success(message);
    }
}
